package cn.com.jinhao.hotline.commons.util;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * @author ShaneWei
 */
public class MessageDigestUtils {


    public static String encrypt(String password, String algorithm) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] b = md.digest(password.getBytes("UTF-8"));
            return ByteUtils.byte2HexString(b);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//	public static void main(String[] args) throws Exception{
//	    Map<String,String> params = new HashMap<>(10);
//	    params.put("appId","hotline");
//	    String value = MessageDigestUtils.getSignatureStr(params);
//	    System.out.println(Objects.requireNonNull(MessageDigestUtils.encrypt(value + "dos4gwcx", Algorithm.MD5)).toUpperCase());
//	}

    public static String getSignatureStr(Map<String, String> params) {
        Map<String, String> sorted = new TreeMap<>();
        params.forEach((k, v) -> {
            if (!"sign".equals(k)) {
                sorted.put(k, v);
            }
        });
        StringBuilder builder = new StringBuilder();
        sorted.forEach((k, v) -> {
            builder.append(k).append("=").append(v).append("&");
        });
        String value = builder.toString();
        return value.substring(0, value.length() - 1);
    }
}
